package com.sn.author.common.sdk;

import lombok.Getter;
import lombok.Setter;
import org.apache.http.entity.ContentType;
import org.springframework.web.bind.annotation.RequestMethod;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Setter
@Getter
public abstract class AbstractRequest {

    private final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    protected String url;

    protected String timestamp;

    protected String version;

    public String j_code;

    protected ContentType contentType = ContentType.create(ContentType.APPLICATION_FORM_URLENCODED.getMimeType(), "UTF-8");

//    protected String baseUrl = "http://192.168.0.107:3030";
//    protected String baseUrl = "http://47.114.166.238:3030";
    protected String baseUrl = "http://139.9.105.162:3030";

    protected String proxyOrder = "930507043614715";

    protected String apiKey = "twol8rg6iaqigkr772h8az4g0xgb9cpk";

    public Long areaCode;

    protected Map<String, Object> urlParamsMap = new HashMap<>();

    //默认为POST方式
    protected String method = RequestMethod.POST.toString();

    public AbstractRequest() {
        this.timestamp = this.sdf.format(new Date());
        this.version = "1.0";
    }

    /**
     * @param method 调用方式 暂时只支持POST和GET 默认POST  如果需要是GET 请调用此构造函数指定
     */
    public AbstractRequest(String method) {
        this.timestamp = this.sdf.format(new Date());
        this.version = "1.0";
        this.method = method;
    }

    public AbstractRequest(String method, ContentType contentType) {
        this.timestamp = this.sdf.format(new Date());
        this.version = "1.0";
        this.method = method;
        this.contentType = contentType;
    }

    protected abstract void setUrlParamsMap(Map<String, Object> map);

    public Object initRequestParams(Map<String, String> paramsMap, String apiUrl) {
        StringBuilder url = new StringBuilder(apiUrl);
        if (paramsMap.keySet().size() == 0) {
            return url.toString();
        }
        url.append("?");
        int i = 0;
        for (String key : paramsMap.keySet()) {
            if (i != 0 && i <= paramsMap.keySet().size() - 1) {
                url.append("&");
            }
            url.append(key);
            url.append("=");
            url.append(paramsMap.get(key));
            i++;
        }
        return url.toString();
    }


}
